﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

// 模拟帧 FE 0F 4B 83 11 22 33 44 55 66 77 88 09 10 11 12 13 14 15 47
namespace ParkingSystem.RxPacket
{
    public struct DCHeartBeat
    {
        public ulong dcIEEEAddress { get; set; }          // field
        public uint channelNum { get; set; }              // field
        public ushort panID { get; set; }                 // field
        public byte seqNumb { get; set; }                 // field
        private const byte _size = 15;
        public static byte size
        {
            get { return _size; }
        }

        private const byte _dcIEEEAddressPos = 0;          // 字段所处起始位置
        public static byte dcIEEEAddressPos
        {
            get { return _dcIEEEAddressPos; }
        }

        private const byte _channelNumPos = 8;              // 字段所处起始位置
        public static byte channelNumPos
        {
            get { return _channelNumPos; }
        }

        private const byte _panIDPos = 12;                   // 字段所处起始位置
        public static byte panIDPos
        {
            get { return _panIDPos; }
        }

        private const byte _seqNumbPos = 14;                  // 字段所处起始位置
        public static byte seqNumbPos
        {
            get { return _seqNumbPos; }
        }

        public const ushort Type = (ushort)0x834B;

        public void Parse(List<byte> rxPacket, int index)      // 对数据进行解析, rxPacket表示原始数据帧,index则表示从DATA起始地址开始解析
        {
            byte[] conver = new byte[8];
            if (conver == null)
                return;

            for (int i = 0; i < 8; i++)
                conver[i] = rxPacket[index + dcIEEEAddressPos + i];
            this.dcIEEEAddress = BitConverter.ToUInt64(conver, 0);

            for (int i = 0; i < 4; i++)
                conver[i] = rxPacket[index + channelNumPos + i];
            this.channelNum = BitConverter.ToUInt32(conver, 0);

            for (int i = 0; i < 2; i++)
                conver[i] = rxPacket[index + panIDPos + i];
            this.panID = BitConverter.ToUInt16(conver, 0);

            this.seqNumb = rxPacket[index + seqNumbPos];
        }

        public override string ToString()
        {

            string s = string.Format("{0,-25} {1,20} {2,15}\n", "(Field)", "(Hex)", "(Decimal)");
            s += string.Format("{0,-25}|{1,20:X4} {2,15:G}\n", "Type", Type, this.GetType().Name);
            s += string.Format("{0,-25}|{1,20:X16}\n", "DCIEEEAddress", this.dcIEEEAddress);
            s += string.Format("{0,-25}|{1,20:X8} {1,15:G}\n", "ChannelNum", this.channelNum);
            s += string.Format("{0,-25}|{1,20:X4} {1,15:G}\n", "PanID", this.panID);
            s += string.Format("{0,-25}|{1,20:X2} {1,15:G}", "SeqNum", this.seqNumb);

            return s;
        }
    }
}